vim.keymap.set("n", "<leader>T", "<cmd>Telescope<cr>", { desc = "open Telescope" })

vim.keymap.set("n", "<leader>S", '<cmd> Spectre<CR>', { desc = 'search and replace' })
vim.keymap.set("n", "<leader>fd", '<cmd>Dired<CR>', { desc = 'find dired' })
vim.keymap.set("n", "<leader>ft", '<cmd>TodoTelescope<CR>', { desc = 'find todos' })
vim.keymap.set('n', "<leader><leader>", "<cmd>Telescope commands<cr>", { desc = "commands" })
vim.api.nvim_set_keymap(
  'n',
  '<leader>fp',
  ":lua require'telescope'.extensions.project.project{}<CR>",
  { noremap = true, silent = true, desc = "find project" })
return {
  {
    "nvim-telescope/telescope.nvim",
    lazy = false,
    init = function()
      local gfh_actions = require("telescope").extensions.git_file_history.actions
      local opts = {
        defaults = {
          preview = {
            filesize_limit = 1,
            timeout = 40,
            highlight_limit = 0.25
          },
          vimgrep_arguments = {
            "rg",
            "-L",
            "--color=never",
            "--no-heading",
            "--with-filename",
            "--line-number",
            "--column",
            "--smart-case",
          },
          prompt_prefix = "   ",
          selection_caret = "  ",
          entry_prefix = "  ",
          initial_mode = "insert",
          selection_strategy = "reset",
          sorting_strategy = "ascending",
          layout_strategy = "horizontal",
          layout_config = {
            horizontal = {
              prompt_position = "top",
              preview_width = 0.55,
              results_width = 0.8,
            },
            -- vertical = {
            --   mirror = false,
            -- },
            width = 0.87,
            height = 0.80,
            preview_cutoff = 120,
          },
          file_sorter = require("telescope.sorters").get_fuzzy_file,
          file_ignore_patterns = { "node_modules" },
          generic_sorter = require("telescope.sorters").get_generic_fuzzy_sorter,
          path_display = { "truncate" },

          -- path_display = function(opts, path)
          --   local tail = require("telescope.utils").path_tail(path)
          --   return string.format("%s|%s", tail, path)
          --   -- , {  { #tail + 3, -1 }, 'Comment'  }
          -- end,
          winblend = 0,
          border = {},
          borderchars = { "─", "│", "─", "│", "╭", "╮", "╯", "╰" },
          color_devicons = true,
          set_env = { ["COLORTERM"] = "truecolor" }, -- default = nil,
          file_previewer = require("telescope.previewers").vim_buffer_cat.new,
          grep_previewer = require("telescope.previewers").vim_buffer_vimgrep.new,
          qflist_previewer = require("telescope.previewers").vim_buffer_qflist.new,
          -- Developer configurations: Not meant for general override
          buffer_previewer_maker = require("telescope.previewers").buffer_previewer_maker,
          mappings = {
            n = { ["q"] = require("telescope.actions").close },
          },
        },

        extensions_list = { "media", "directory", "project", "git_file_history" },
        extensions = {
          -- media_files = {
          --   -- filetypes whitelist
          --   -- defaults to {"png", "jpg", "mp4", "webm", "pdf"}
          --   filetypes = { "png", "webp", "jpg", "jpeg" },
          --   -- find command (defaults to `fd`)
          --   find_cmd = "rg",
          -- },
          git_file_history = {
            -- Keymaps inside the picker
            mappings = {
              i = {
                ["<C-g>"] = gfh_actions.open_in_browser,
              },
              n = {
                ["<C-g>"] = gfh_actions.open_in_browser,
              },
            },

            -- The command to use for opening the browser (nil or string)
            -- If nil, it will check if xdg-open, open, start, wslview are available, in that order.
            browser_command = nil,
          },
        },
      }

      require("telescope").setup(opts)
      local list = { 'project', 'directory', 'media', 'git_file_history' }
      for _, extension in ipairs(list) do
        require('telescope').load_extension(extension)
      end


      local builtin = require('telescope.builtin')

      vim.keymap.set('n', '<leader>ff', '<cmd>Telescope find_files<cr>', { desc = "find_files" })
      vim.keymap.set('n', '<leader>ch', "<cmd> Telescope keymaps<CR>", { desc = 'cheatsheet' })

      vim.keymap.set("n", "<leader>gm", builtin.git_commits, { desc = "git checkout commits" })
      vim.keymap.set("n", "<leader>gs", builtin.git_status, { desc = "git status " })
      vim.keymap.set("n", "<leader>gB", builtin.git_branches, { desc = "git switch branches" })
      vim.keymap.set("n", "<leader>gh", require("telescope").extensions.git_file_history.git_file_history,
        { desc = "git show current file history" })

      local Path = require "plenary.path"
      local lookup_keys = {
        ordinal = 1,
        value = 1,
        filename = 1,
        cwd = 2,
      }

      local handle_entry_index = function(opts, t, k)
        local override = ((opts or {}).entry_index or {})[k]
        if not override then
          return
        end

        local val, save = override(t, opts)
        if save then
          rawset(t, k, val)
        end
        return val
      end
      function gen_from_file(opts)
        opts = opts or {}
        local utils = require "telescope.utils"
        local cwd = vim.fn.expand(opts.cwd or vim.loop.cwd())

        local disable_devicons = opts.disable_devicons

        local mt_file_entry = {}

        mt_file_entry.cwd = cwd
        mt_file_entry.display = function(entry)
          local hl_group, icon
          local display = utils.transform_path(opts, entry.value)

          local basename = utils.path_tail(entry.value)
          display, hl_group, icon = utils.transform_devicons(entry.value, display, disable_devicons)
          if hl_group then
            local final = icon .. ' ' .. basename .. ' ' .. display
            return final, { { { 0, #icon }, hl_group }, { { #icon + #basename + 3, #final }, 'Comment' } }
          else
            return display
          end
        end

        mt_file_entry.__index = function(t, k)
          local override = handle_entry_index(opts, t, k)
          if override then
            return override
          end

          local raw = rawget(mt_file_entry, k)
          if raw then
            return raw
          end

          if k == "path" then
            local retpath = Path:new({ t.cwd, t.value }):absolute()
            if not vim.loop.fs_access(retpath, "R", nil) then
              retpath = t.value
            end
            return retpath
          end

          return rawget(t, rawget(lookup_keys, k))
        end

        return function(line)
          return setmetatable({ line }, mt_file_entry)
        end
      end

      vim.keymap.set('n', '<leader>ff', function()
        builtin.find_files(vim.tbl_extend('force', require('telescope.themes').get_dropdown {
          previewer = false
        }, {
          wrap_results = true,
          color_devicons = true,
          entry_maker = gen_from_file(),

          layout_config = {
            width = 0.8, -- Adjust this value to set the width as a fraction of the total window width
          },
        }))
      end, { desc = 'find files' })

      vim.keymap.set('n', '<leader>pt', function()
        builtin.colorscheme { enable_preview = true }
      end, { desc = 'pick a theme' })
      vim.keymap.set('n', '<leader>fa', function()
        builtin.find_files {
          no_ignore = true,
          hidden = true,
          wrap_results = true,
          entry_maker = gen_from_file(),
          previewer = false,
          layout_config = {
            width = 0.8
          }

        }
      end, { desc = 'find all files' })
      vim.keymap.set('n', '<leader>fw', function()
        builtin.live_grep {
          preview = {
            filesize_limit = 1,
            highlight_limit = 0.8,
            timeout = 40,
          },

        }
      end, { desc = 'find words' })
      vim.keymap.set('n', '<leader>fb', builtin.buffers, { desc = 'find buffers' })
      vim.keymap.set('n', '<leader>fs', builtin.lsp_document_symbols, { desc = 'find symbols' })
      vim.keymap.set('n', '<leader>fo', function()
        builtin.oldfiles {

          entry_maker = gen_from_file(),

          preview = {
            filesize_limit = 1,
            highlight_limit = 0.8,
            timeout = 40
          },
        }
      end, { desc = 'find old files' })

      vim.keymap.set("n", "<leader>fg", require('telescope.builtin').git_files, { desc = "find git files" })
      vim.keymap.set('n', '<leader>fh', builtin.help_tags, {
        desc = 'find help tags'
      })
      vim.keymap.set('n', '<leader>ld', builtin.diagnostics, { desc = 'diagnostics' })
    end,

    dependencies = {
      "nvim-lua/plenary.nvim",
      "dharmx/telescope-media.nvim",
      "fbuchlak/telescope-directory.nvim",
      "nvim-telescope/telescope-project.nvim",
      {
        "isak102/telescope-git-file-history.nvim",
        dependencies = { "tpope/vim-fugitive" }
      },
    },
  },

  -- {
  --   "s1n7ax/nvim-search-and-replace",
  --   config = function()
  --     require("nvim-search-and-replace").setup()
  --   end,
  -- },
  {
    "nvim-pack/nvim-spectre",
    opts = {

    }
  },
}
